package com.cjf.spring.cloud.weather.service.impl;

import com.cjf.spring.cloud.weather.service.WeatherDataService;
import com.cjf.spring.cloud.weather.vo.Weather;
import com.cjf.spring.cloud.weather.vo.WeatherResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;

/**
* @description 
* @author  cjf
* @create 2019-03-26 16:53
*/
@Service
public class WeatherDataServiceImpl implements WeatherDataService {

    /** 通过城市id查询:http://wthrcdn.etouch.cn/weather_mini?citykey=101280601
     *  通过城市名字查询：http://wthrcdn.etouch.cn/weather_mini?city=深圳
     *  查询城市id：http://mobile.weather.com.cn/js/citylist.xml
     */

    private static final  String WEATHER_URL = "http://wthrcdn.etouch.cn/weather_mini?";

    @Autowired
    private RestTemplate restTemplate;

    @Override
    public WeatherResponse getDataByCityId(String cityId) {
        String url = WEATHER_URL + "citykey=" + cityId;
        return doGetWeather(url);
    }

    @Override
    public WeatherResponse getDataByCityName(String name) {
        String url = WEATHER_URL + "city=" + name;
        return doGetWeather(url);
    }

    private WeatherResponse doGetWeather(String url){
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url,String.class);
        WeatherResponse weatherResponse = null;
        if(responseEntity.getStatusCodeValue() == 200){
            ObjectMapper objectMapper = new ObjectMapper();
            String content = responseEntity.getBody();
            System.out.println(content);
            try {
                weatherResponse = objectMapper.readValue(content,WeatherResponse.class);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return weatherResponse;
    }
}
